
package com.ifcar.app.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;

public class PageClickView extends ImageView implements GestureDetector.OnGestureListener {

    private GestureDetector mDetector;
    
    private PerformClick mPerformClick;

    public PageClickView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public PageClickView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PageClickView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        mDetector = new GestureDetector(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDetector.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPerformClick = new PerformClick();
                setPressed(true);
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (mPerformClick != null) {
                    post(mPerformClick);
                    mPerformClick = null;
                }
                setPressed(false);
                break;

            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        removePerformClick();
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        removePerformClick();
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return true;
    }
    
    private void removePerformClick() {
        if (mPerformClick != null) {
            mPerformClick = null;
        }
    }

    private class PerformClick implements Runnable {
        @Override
        public void run() {
            performClick();
        }
    }
}
